import { computed } from 'vue'
import type { Ref } from 'vue'
import { mapGetters, mapState, useStore, createNamespacedHelpers } from 'vuex'
type MapStateRef = { [key:string]:Ref }
const useMapper = (mapper: string[], mapFn = mapState):MapStateRef => {
	const store = useStore()
	const storeStateFns = mapFn(mapper)
	const storeState:MapStateRef = {}
	Object.keys(storeStateFns).forEach((keyFn) => {
		const fn = storeStateFns[keyFn].bind({ $store: store })
		storeState[keyFn] = computed(fn)
	})
	return storeState
}

export const useState = (moduleName: string[] | string, mapper?: string[]):MapStateRef => {
	let mapperFn = mapState
	if (typeof moduleName === 'string' && moduleName) {
		mapperFn = createNamespacedHelpers(moduleName).mapState
	} else {
		mapper = moduleName as string[]
	}
	return useMapper(mapper as string[], mapperFn)
}

export const useGetters = (moduleName: string[] | string, mapper?: string[]):MapStateRef => {
	let mapperFn = mapGetters
	if (typeof moduleName === 'string' && moduleName.length > 0) {
		mapperFn = createNamespacedHelpers(moduleName).mapGetters
	} else {
		mapper = moduleName as string[]
	}
	return useMapper(mapper as string[], mapperFn)
}
